#include "../include/gps_utils.h"
#include <pthread.h>

// 全局变量定义
VehicleSensor_t vehicle_sensor = {0.0f, false, 0, false, 0.0f, 0.0f};
uint32_t log_cycle_count = 0;
extern pthread_mutex_t lock;

// 初始化模块
void VehicleSensor_Init(void) {
    srand((unsigned int)time(NULL));
    vehicle_sensor.current_speed = 0.0f;
    vehicle_sensor.alarm_active = false;
    vehicle_sensor.module_active = true;
    vehicle_sensor.fuel_level = 100.0f;
    vehicle_sensor.temperature = 20.0f;
    HAL_GPIO_WritePin(GPIO_PIN_6, GPIO_PIN_SET);
    
    char log_entry[MAX_LOG_ENTRY];
    snprintf(log_entry, MAX_LOG_ENTRY, "[Cycle 0] Module initialized, Speed: %.2f km/h, Fuel: %.2f%%, Temperature: %.2f°C\n", 
             vehicle_sensor.current_speed, vehicle_sensor.fuel_level, vehicle_sensor.temperature);
    HAL_UART_Transmit(0, (uint8_t*)log_entry, strlen(log_entry), UART_TIMEOUT);
    
    FILE* fp = fopen(LOG_FILE, "a");
    if (fp) {
        fwrite(log_entry, 1, strlen(log_entry), fp);
        fclose(fp);
    }
}

// 读取ADC并计算速度
float VehicleSensor_ReadSpeed(void) {
    uint32_t adc_value = HAL_ADC_GetValue(0);
    float voltage = (adc_value * VREF_VOLTAGE) / ADC_MAX_VALUE;
    float speed_kmh = (voltage / VREF_VOLTAGE) * MAX_SPEED_KMH;
    return speed_kmh;
}

// 模拟读取油量
float VehicleSensor_ReadFuel(void) {
    vehicle_sensor.fuel_level -= (float)(rand() % 10) / 100.0f;
    if (vehicle_sensor.fuel_level < 0.0f) vehicle_sensor.fuel_level = 100.0f;
    return vehicle_sensor.fuel_level;
}

// 模拟读取温度
float VehicleSensor_ReadTemperature(void) {
    vehicle_sensor.temperature = 15.0f + (float)(rand() % 7000) / 100.0f;
    return vehicle_sensor.temperature;
}

// 记录日志
void VehicleSensor_Log(void) {
    char log_entry[MAX_LOG_ENTRY];
    log_cycle_count++;
    
    snprintf(log_entry, MAX_LOG_ENTRY, "[Cycle %u] Speed: %.2f km/h, Fuel: %.2f%%, Temperature: %.2f°C, Alarm: %d, Module: %d\n",
             log_cycle_count, vehicle_sensor.current_speed, vehicle_sensor.fuel_level, 
             vehicle_sensor.temperature, vehicle_sensor.alarm_active, vehicle_sensor.module_active);
    
    HAL_UART_Transmit(0, (uint8_t*)log_entry, strlen(log_entry), UART_TIMEOUT);
    
    FILE* fp = fopen(LOG_FILE, "a");
    if (fp) {
        fwrite(log_entry, 1, strlen(log_entry), fp);
        fclose(fp);
    }
}

// 处理逻辑（无打印）
void VehicleSensor_Process(void) {
    pthread_mutex_lock(&lock);
    vehicle_sensor.adc_raw_value = HAL_ADC_GetValue(0);
    vehicle_sensor.current_speed = VehicleSensor_ReadSpeed();
    vehicle_sensor.fuel_level = VehicleSensor_ReadFuel();
    vehicle_sensor.temperature = VehicleSensor_ReadTemperature();
    
    if (vehicle_sensor.current_speed > SPEED_THRESHOLD) {
        vehicle_sensor.alarm_active = true;
        HAL_GPIO_WritePin(GPIO_PIN_5, GPIO_PIN_SET);
    } else {
        vehicle_sensor.alarm_active = false;
        HAL_GPIO_WritePin(GPIO_PIN_5, GPIO_PIN_RESET);
    }
    
    if (vehicle_sensor.module_active) {
        HAL_GPIO_WritePin(GPIO_PIN_6, GPIO_PIN_SET);
    } else {
        HAL_GPIO_WritePin(GPIO_PIN_6, GPIO_PIN_RESET);
    }
    
    VehicleSensor_Log();
    pthread_mutex_unlock(&lock);
    
    HAL_Delay(SAMPLING_PERIOD_MS);
}

// 后台传感器处理
void VehicleSensor_Background(void) {
    VehicleSensor_Init();
    while (run_sensor) {
        VehicleSensor_Process();
        sleep(1);
    }
}

// 前台传感器控制（处理打印和输入）
int VehicleSensor_Foreground(void) {
    printf("车辆传感器监测运行中，按 'q' 退出（无需 Enter）...\n");
    while (1) {
        if (check_exit()) {
            printf("退出车辆传感器监测，前台模式结束（后台继续运行）\n");
            break;
        }
        pthread_mutex_lock(&lock);
        printf("速度: %.2f km/h\n", vehicle_sensor.current_speed);
        printf("油量: %.2f%%\n", vehicle_sensor.fuel_level);
        printf("温度: %.2f°C\n", vehicle_sensor.temperature);
        printf("报警状态: %d\n", vehicle_sensor.alarm_active);
        printf("模块状态: %d\n", vehicle_sensor.module_active);
        putchar('\n');
        pthread_mutex_unlock(&lock);
        sleep(1);
    }
    return 0;
}

// 获取当前速度
float VehicleSensor_GetSpeed(void) {
    return vehicle_sensor.current_speed;
}

// 获取油量
float VehicleSensor_GetFuel(void) {
    return vehicle_sensor.fuel_level;
}

// 获取温度
float VehicleSensor_GetTemperature(void) {
    return vehicle_sensor.temperature;
}

// 获取报警状态
bool VehicleSensor_IsAlarmActive(void) {
    return vehicle_sensor.alarm_active;
}

// 获取模块运行状态
bool VehicleSensor_IsModuleActive(void) {
    return vehicle_sensor.module_active;
}

// 原 VehicleSensor_Main 保留为兼容性（可选）
int VehicleSensor_Main(void) {
    return VehicleSensor_Foreground();
}